<template>
  <div class="app-container home">
    <div v-if="!open && !isView"
         class="body">
      <el-form :model="queryParams"
               ref="queryForm"
               size="small"
               :inline="true"
               label-width="68px">
        <el-form-item label="标题"
                      prop="title">
          <el-input v-model="queryParams.title"
                    placeholder="请输入标题"
                    clearable
                    @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="发布时间"
                      prop="publishDate">
          <el-date-picker clearable
                          v-model="queryParams.publishDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="文章类型"
                      prop="type">
          <el-select v-model="queryParams.type"
                     placeholder="请选择文章类型">
            <el-option v-for="dict in dict.type.sys_science_type"
                       :key="dict.value"
                       :label="dict.label"
                       :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     icon="el-icon-search"
                     size="mini"
                     @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh"
                     size="mini"
                     @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10"
              class="mb8">
        <el-col :span="1.5">
          <el-button type="primary"
                     plain
                     icon="el-icon-plus"
                     size="mini"
                     @click="handleAdd">新增</el-button>
        </el-col>
      </el-row>
      <div style="display: flex;justify-content: center"
           v-if="scienceList.length < 1">
        <el-image :src="noData"
                  fit="fill"></el-image>
      </div>
      <el-row v-if="scienceList.length > 0"
              class="article-list-all"
              :gutter="24">
        <el-col v-for="(item, index) in scienceList"
                :key="index"
                :span="24">
          <el-card class="article-list"
                   shadow="hover">
            <div class="article-data">
              <span>{{ item.createTime }}</span>
              <div class="article-tag">
                <el-tag v-if="item.publishStatus === '0'">已发布</el-tag>
                <el-tag v-if="item.publishStatus === '1'">已下架</el-tag>
              </div>
            </div>
            <div class="article-image">
              <el-image style="width: 100px; height: 100px"
                        :src="item.cover ? item.cover : ''"
                        fit="fill"></el-image>
            </div>
            <div class="article-title">
              <div class="title">{{ item.title }}
                <template v-for="a in dict.type.sys_science_type">
                  <el-tag v-if="a.value === item.type"
                          style="margin-left: 20px">{{ a.label }}</el-tag>
                </template>
              </div>
              <div class="title-icon">
                <div class="browse">
                  <i class="el-icon-view" />
                  <span class="num">{{ item.viewNum }}</span>
                </div>
                <!--                <div class="retransmission">-->
                <!--                  <i class="el-icon-view" />-->
                <!--                  <span class="num">1</span>-->
                <!--                </div>-->
                <!--                <div class="give">-->
                <!--                  <i class="el-icon-view" />-->
                <!--                  <span class="num">1</span>-->
                <!--                </div>-->
              </div>
            </div>
            <div class="article-bottom">
              <el-button @click="handleEdit(item)"
                         circle>改</el-button>
              <el-button @click="handleDelete(item)"
                         circle>删</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <div class="page">
        <pagination v-show="total>0"
                    :total="total"
                    :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList" />
      </div>
    </div>
    <!-- 添加或修改留言对话框 -->
    <div v-if="open && !isView"
         class="editdata">
      <p class="back"><span class="el-icon-arrow-left"
              @click="goBack">返回</span> / <span>{{title}}</span></p>

      <el-form ref="form"
               :model="form"
               :rules="rules"
               label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="文章标题"
                          prop="title">
              <el-input v-model="form.title"
                        placeholder="请输入文章标题" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文章类型"
                          prop="type">
              <el-select v-model="form.type"
                         placeholder="请选择文章类型">
                <el-option v-for="dict in dict.type.sys_science_type"
                           :key="dict.value"
                           :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态">
              <el-radio-group v-model="form.publishStatus">
                <el-radio label="0">已发布</el-radio>
                <el-radio label="1">已下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="20">
            <el-form-item label="文章内容">
              <editor api-key="4ed6kvrs1pq3f86i1z9bau4jjbrbr71e642vkzjty2zqxiqd"
                      v-model="content"
                      :init="editorInit"
                      :disabled="(nodedata.level !== 3)||show"
                      :min-height="300" />
            </el-form-item>

            <el-form-item label="封面">
              <DragUpload1 v-model="form.cover" :data="messageFileList"
                           @input="uploadInput" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import noData from '@/assets/images/no_data.png'
import DragUpload1 from "@/components/DragUpload/indexCover.vue";
import { addScience, delScience, listScience, updateScience } from "@/api/system/article/science";
import {Base64} from 'js-base64'
export default {
  name: 'scienceIndex',
  dicts: ['sys_science_type'],
  components: {
    DragUpload1
  },
  data () {
    return {
      noData: noData,
      // 遮罩层
      loading: true,
      show: null,
      nodedata: {},
      rules: {
        title: [
          { required: true, message: "文章标题不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "文章类型不能为空", trigger: "change" }
        ],
        content: [
          { required: true, message: "文章内容不能为空", trigger: "blur" }
        ]
      },
      // 总条数
      total: 0,
      messageFileList: [],
      // 科普知识表格数据
      scienceList: [],
      content: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        publishStatus: "0",
        publishDate: null,
        cover: null,
        digest: null,
        type: null,
        content: null
      },
      form: {
        publishStatus: "0"
      },
      title: '',
      // 是否显示弹出层
      open: false,
      isView: false, //是否查看页面
      editorInit: {
        language: 'zh_CN',
        menubar: false,
        height: 500,
        convert_urls: false,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen  image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: [' bold  italic  underline strikethrough  blockquote code  alignleft aligncenter alignright outdent indent   undo redo removeformat subscript superscript  codesample', ' bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: (blobInfo, success, failure) => {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          // uploadFile(formData).then(res => {
          //   success(res.data.url)
          // }).catch(() => {
          //   failure('上传失败，请重新上传')
          // })
        }
      }
    }
  },
  created () {
    this.getList();
  },
  methods: {
    uploadInput (val) {
      this.messageFileList = val
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 查询科普知识列表 */
    getList () {
      this.loading = true;
      listScience(this.queryParams).then(response => {
        this.scienceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    goBack () {
      this.open = false
      this.isView = false
      this.reset()
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    /**
     * 新增
     */
    handleAdd () {
      this.messageFileList = [];
      this.open = true
      this.title = '新增文章'
    },
    handleEdit (val) {
      this.open = true
      this.title = '编辑文章'
      this.form = val
      this.content = Base64.decode(this.form.digest)
      this.messageFileList = [{'url' : val.cover}]
    },
    /** 提交按钮 */
    submitForm () {
      var that = this;
      this.$refs["form"].validate(valid => {
        if (!that.content) {
          that.$modal.msgWarning("文章内容不能为空")
          valid = false
        }
        if (!that.form.cover) {
          that.$modal.msgWarning("文章封面不能为空")
          valid = false
        }
        if (valid) {
          that.form.digest = Base64.encode(that.content)
          var url = that.form.cover[0].url;
          that.form.cover = url;
          if (that.form.id != null) {
            updateScience(that.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addScience(that.form).then(response => {
              that.$modal.msgSuccess("新增成功");
              that.open = false;
              that.getList();
            });
          }
          this.reset();
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除当前科普知识数据项？').then(function () {
        return delScience(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        title: null,
        publishStatus: "0",
        publishDate: null,
        cover: null,
        digest: null,
        type: null,
        content: null
      };
      this.content = null
      this.resetForm("form");
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-col {
  margin-bottom: 20px;
}
.body {
  height: 100%;
}
.article-list {
  height: 145px;
  width: 100%;
  ::v-deep .el-card__body {
    cursor: pointer;
    display: flex;
    .article-image {
      width: 15%;
      display: flex;
      justify-content: center;
    }
    ::v-deep .el-image {
      display: inline-block;
    }
    .article-data {
      font-size: 14px;
      width: 12%;
      .article-tag {
        margin-top: 10px;
      }
    }
    .article-title {
      font-size: 14px;
      width: 60%;
      .title {
        margin-bottom: 20px;
      }
      .title-icon {
        display: flex;
        .retransmission {
          margin-left: 40px;
        }
        .give {
          margin-left: 40px;
        }
        .num {
          margin-left: 10px;
        }
      }
    }
    .article-bottom {
      display: flex;
      align-items: center;
    }
  }
}
.article-list-all {
  height: calc(100% - 150px);
  overflow: auto;
}
.page {
  margin-top: 10px;
  height: 30px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.editdata {
  width: 100%;
  height: calc(100% - 20px);
  overflow: auto;
  background: #ffffff;
  border-radius: 0px 0px 0px 0px;
  padding: 1px 20px;
  box-sizing: border-box;
  // 面包屑样式
  .back {
    .el-icon-arrow-left {
      color: #979797;
      cursor: pointer;
    }
    span {
      font-size: 14px;
      font-family: Source Code Pro-Regular, Source Code Pro;
      font-weight: 400;
      color: #1f2329;
      line-height: 22px;
    }
  }
  // form表单样式
  .editbox {
    padding: 20px;
    box-sizing: border-box;
    background: #ffffff;
    box-shadow: 0px 4px 12px 0px rgba(211, 211, 211, 0.25);
    border-radius: 6px 6px 6px 6px;
  }
  .editfooter {
    margin-top: 20px;
    > div {
      display: flex;
      padding-bottom: 44px;
      .footbox {
        width: 150px;
        height: 96px;
        background: #f7f8fa;
        border-radius: 4px 4px 4px 4px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 20px;
        position: relative;
        cursor: pointer;
        img {
          width: 23px;
          height: 24px;
        }
        .icon_box {
          width: 16px;
          height: 16px;
          position: absolute;
          right: 10px;
          top: 10px;
        }
      }
    }
  }

  h3 {
    font-family: Source Code Pro-Bold, Source Code Pro;
    font-weight: bold;
    color: #1f2329;
    line-height: 24px;
    margin: 0 0 20px 0;
    padding: 0;
  }
}
</style>
